//
//  MovieDetailViewController.m
//  YHYRealx
//
//  Created by yanghuiyan on 16/4/20.
//  Copyright © 2016年 yanghuiyan. All rights reserved.
//

#import "MovieDetailViewController.h"
//#import "YHYBaseView.h"
@interface MovieDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, retain) NSMutableArray *dataSource;

@property (nonatomic, retain) NSMutableArray *playArr;

@property (nonatomic, retain) MoviePlayModel *playModel;

@property (nonatomic, retain) MovieDataModel *dataModel;

@property (nonatomic, retain) UIView *topView;

@property (nonatomic, retain) UIImageView *pic; //顶部图片

@property (nonatomic, retain) YHYBaseTableView *tableView;

@property (nonatomic, assign) CGFloat cellHeight;

@property (nonatomic, retain) YHYBaseView *playView; //播放的View

@property (nonatomic, retain) YHYAVPlayer *MVPlayer; //播放的player

@property (nonatomic, retain) AVPlayerItem *item; //播放item

@property (nonatomic, retain)UIButton *playClickbutton; //播放按钮

@property (nonatomic, retain)UISlider *slider; //播放进度条

@property (nonatomic, assign) CGFloat totalMovieDuration;//  保存该视频资源的总时长，快进或快退的时候要用

@property (nonatomic, retain)NSTimer *sliderTime; //播放时间

@property (nonatomic, retain)UILabel *timeLabel; //播放时间label

@property (nonatomic, retain)YHYBaseView *BtuClickView; //播放按钮、进度背景

@property (nonatomic, retain)UIButton *plusButton; //全屏按钮

@property (nonatomic, retain) UIButton *favoriteButton; //收藏按钮

@property (nonatomic, retain) UIButton *shareButton; //分享按钮

@property (nonatomic, retain) YHYBaseView *speedView;

@property (nonatomic, retain) UIButton *backButton; //快退按钮

@property (nonatomic, retain) UIButton *goButton; //快进按钮

@property (nonatomic, retain) UIButton *delectButton; //取消按钮

@property (nonatomic, assign)BOOL isplay; //判断是否播放

@property (nonatomic, assign)BOOL isplus; //判断是否横屏

@property (nonatomic, assign) BOOL isShare; //判断是否收藏

@property (nonatomic, assign) BOOL isHave; //判断数据库中是否存在此页数据

@property (nonatomic, assign) BOOL LOAD; //判断刷新

@property (nonatomic, assign) BOOL isHidden; // 判断playView手势

@end

@implementation MovieDetailViewController

- (void)dealloc {
    
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
    
    [_tableView release];
    [_dataModel release];
    [_dataSource release];
    [_playArr release];
    [_playModel release];
    [_dataModel release];
    [_topView release];
    [_pic release];
    [_tableView release];
    [_playView release];
    [_MVPlayer release];
    [_item release];
    [_playClickbutton release];
    [_slider release];
    [_sliderTime release];
    [_timeLabel release];
    [_BtuClickView release];
    [_speedView release];
    
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataSource = [NSMutableArray array];
    
    [self creatView];
    [self dataHandle];
    [self playDataHandle];
    
    
}

#pragma mark - 创建视图
- (void)creatView {
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    titleLabel.text = self.titl;
    titleLabel.font = [UIFont boldSystemFontOfSize:22];
    titleLabel.textColor = [UIColor grayColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    [titleLabel release];
    
    //导航栏左侧按钮
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"< 电影" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemAction:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    // 创建tableView
    self.tableView = [[YHYBaseTableView alloc] initWithFrame:CGRectMake(0, HEIGHT * 0.3, WIDTH, HEIGHT * 0.7 - 114) style:UITableViewStylePlain];
    [_tableView registerClass:[MovieDetailTableViewCell class] forCellReuseIdentifier:@"movieDetail"];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
    [_tableView release];
    
    
}

- (void)leftItemAction:(UIBarButtonItem *)sender {
    
    [self.MVPlayer pause];
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark - 数据解析

- (void)dataHandle {
    
    NSString *string = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/movie/%@/story/1/0", self.idNew];
    
    [YHYAFNetTool GETNetWirhUrl:string body:nil headerFile:nil response:YHYJSON Success:^(id result) {
        
        for (NSDictionary *dic in result[@"data"][@"data"]) {
            
            self.dataModel =[[MovieDataModel alloc] initWithDataSource:dic];
            
            [self.dataSource addObject:_dataModel];
            
        }
        
        [self.tableView reloadData];
        
    } Failure:^(NSError *error) {
        
    }];
    
}

- (void)playDataHandle {
    
    NSString *string = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/movie/detail/%@", self.idNew];
    
    [YHYAFNetTool GETNetWirhUrl:string body:nil headerFile:nil response:YHYJSON Success:^(id result) {
        
        self.playModel = [[MoviePlayModel alloc] initWithDataSource:result[@"data"]];
        
        [self.playArr addObject:self.playModel];
        
        NSLog(@"%@", self.playModel.video);
        
        // 顶部视图
        [self TopView];
        
    } Failure:^(NSError *error) {
        
    }];
    
}

/**
 *  顶部视图
 */
- (void)TopView {
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT * 0.3 + 20)];
    _topView.backgroundColor = [UIColor grayColor];
    self.pic = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT * 0.3 + 20)];
    [_pic sd_setImageWithURL:[NSURL URLWithString:self.playModel.detailcover]];
    [_topView addSubview:_pic];
    [self.view bringSubviewToFront:_topView];
    [self.view addSubview:_topView];
    
    // 打开图片交互
    _pic.userInteractionEnabled =YES;
    
    // 给图片添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [tap addTarget:self action:@selector(tapAction:)];
    [_pic addGestureRecognizer:tap];
    
    [_topView release];
    [_pic release];
    [tap release];

}

#pragma mark - 头部视图手势
- (void)tapAction:(UITapGestureRecognizer *) sender {
    
    // 判断是否存在当前播放页面、若存在则移除
    if (_playView) {
        
        [_playView removeFromSuperview];
        
        [_MVPlayer pause];
        
    }
    
    /**
     *  创建播放页面
     */
    self.playView = [[YHYBaseView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT * 0.3 + 20)];
    _playView.backgroundColor = [UIColor blackColor];
    [_topView addSubview:_playView];
    
    
    /**
     *  给播放页面添加手势 点击隐藏BtuClickView和speedView
     */
    UITapGestureRecognizer *playViewTap = [[UITapGestureRecognizer alloc] init];
    [playViewTap addTarget:self action:@selector(playViewTapAction:)];
    [_playView addGestureRecognizer:playViewTap];
    _isHidden = YES;


    /**
     *  创建播放
     */
    self.MVPlayer = [YHYAVPlayer shareYHYAVPlayer];
    self.MVPlayer.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_MVPlayer];
    self.MVPlayer.playerLayer.frame = _playView.bounds;
//    self.MVPlayer.playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
    [_playView.layer addSublayer:self.MVPlayer.playerLayer];
    
    // 播放
    [_MVPlayer playWithURL:self.playModel.video];
    [_MVPlayer play];
    
    
    /**
     *  创建放button和slider的view
     */
    self.BtuClickView = [[YHYBaseView alloc]initWithFrame:CGRectMake(0, self.playView.bounds.size.height * 0.9, self.playView.bounds.size.width, self.playView.bounds.size.height * 0.1)];
    self.BtuClickView.backgroundColor = [UIColor blackColor];
    self.BtuClickView.alpha = 0.5;
    [self.playView addSubview:self.BtuClickView];
    
    
    /**
     *  创建播放按钮
     */
    self.playClickbutton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.playClickbutton.frame = CGRectMake(5, 0, self.BtuClickView.frame.size.height, self.BtuClickView.frame.size.height);
    [_playClickbutton setImage:[[UIImage imageNamed:@"视频暂停"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    // 添加点击事件
    [_playClickbutton addTarget:self action:@selector(clickbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.BtuClickView addSubview:self.playClickbutton];
    _isplay = YES;
    
    
    
    /**
     *  创建滑动进度slider
     */
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(self.BtuClickView.frame.size.width * 0.15, 5, self.BtuClickView.frame.size.width * 0.4, self.BtuClickView.bounds.size.height - 10)];
    _slider.minimumValue = 0.1;
    _slider.maximumValue = 1.0;
    [_slider setThumbImage:[[UIImage imageNamed:@"视频slider"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] forState:UIControlStateNormal];
    // 添加事件
    [_slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.BtuClickView addSubview:self.slider];
    // 创建定时器 设置slider
    _sliderTime = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(sliderTimeAction) userInfo:nil repeats:YES];
    // 创建timelabel来承接时间
    self.timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.BtuClickView.frame.size.width * 0.6, 0, self.BtuClickView.frame.size.width * 0.3, self.BtuClickView.frame.size.height)];
    
    
    /**
     *  创建全屏按钮
     */
    self.plusButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _plusButton.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.9, 0, 20, 20);
    [_plusButton addTarget:self action:@selector(plusButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_plusButton setImage:[[UIImage imageNamed:@"视频全屏"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.BtuClickView addSubview:_plusButton];
    _isplus = YES;
    
    
    /**
     *  创建快进 快退按钮
     */
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _backButton.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.1, 0, 20, 20);
    [_backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_backButton setImage:[[UIImage imageNamed:@"快退"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.BtuClickView addSubview:_backButton];
    
    self.goButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _goButton.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.55 - 3, 0, 20, 20);
    [_goButton addTarget:self action:@selector(goButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_goButton setImage:[[UIImage imageNamed:@"快进"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.BtuClickView addSubview:_goButton];

    
    
    /**
     *  创建取消的view
     */
    self.speedView = [[YHYBaseView alloc] initWithFrame:CGRectMake(0, 0, self.playView.bounds.size.width, self.playView.bounds.size.height * 0.1)];
    self.speedView.backgroundColor = [UIColor blackColor];
    self.speedView.alpha = 0.5;
    [self.playView addSubview:_speedView];
    
    
    /**
     *  创建取消按钮
     */
    self.delectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _delectButton.frame = CGRectMake(self.speedView.frame.size.width * 0.95, 0, 20, 20);
    [_delectButton addTarget:self action:@selector(delectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_delectButton setImage:[[UIImage imageNamed:@"取消"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.speedView addSubview:_delectButton];
    
    [_playView release];
    [_MVPlayer release];
    [_BtuClickView release];
    [_speedView release];
    [_slider release];
    
}

#pragma mark - playView手势
- (void)playViewTapAction:(UIButton *)sender {
    
    if (_isHidden == YES) {
        
        self.BtuClickView.hidden = YES;
        self.speedView.hidden = YES;
        _isHidden = NO;
        
    }else {
        
        self.BtuClickView.hidden = NO;
        self.speedView.hidden = NO;
        _isHidden = YES;
    }
    
    
}

#pragma mark - 播放暂停点击事件
- (void)clickbuttonAction:(UIButton *)sender {
    
    if (_isplay == YES) {
        
        [self.MVPlayer pause];
        [_playClickbutton setImage:[UIImage imageNamed:@"视频播放"] forState:UIControlStateNormal];
        _isplay = NO;
    
    } else {
        
        [self.MVPlayer play];
        [_playClickbutton setImage:[UIImage imageNamed:@"视频暂停"] forState:UIControlStateNormal];
        _isplay = YES;
        
    }
    
}


#pragma mark - 观察者 观察播放完毕
- (void)addNotificationCenters {
    //  注册观察者用来观察，是否播放完毕
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

#pragma mark 播放结束后的代理回调
- (void)moviePlayDidEnd:(NSNotification *)notify
{
    
    [self.playView removeFromSuperview];
    
}



#pragma mark - 进度slider事件

- (void)sliderAction:(UISlider *)sender {
    
    //    跳转到的时间
    //    每秒多少帧
    if (self.MVPlayer.currentItem.duration.value ) {
        
        [self.MVPlayer seekToTime:CMTimeMakeWithSeconds(self.MVPlayer.currentItem.duration.value / self.MVPlayer.currentItem.duration.timescale * self.slider.value, self.MVPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
            
            [self.MVPlayer play];
            
        }];
        
    }

    
}

#pragma mark - 定时器与slider关联

- (void)sliderTimeAction {
    
    //设置进度值 当前时间/总时长
    self.slider.value = CMTimeGetSeconds(self.MVPlayer.currentItem.currentTime) / CMTimeGetSeconds(self.MVPlayer.currentItem.duration);
    
#pragma mark - 创建时间
    
    CMTime presentTime = self.MVPlayer.currentItem.currentTime;
    
    CMTime totalTime = self.MVPlayer.currentItem.duration;
    
    CGFloat presentFloatTim = (CGFloat)presentTime.value/presentTime.timescale;
    
    CGFloat totalFloatTim = (CGFloat)totalTime.value / totalTime.timescale;
    
    //保存总时长用于手动快进和快退
    _totalMovieDuration = totalFloatTim;
    
    self.slider.value = presentFloatTim / totalFloatTim;
    
    NSDate *presentDate = [NSDate dateWithTimeIntervalSince1970:presentFloatTim];
    
    NSDate *totalDate = [NSDate dateWithTimeIntervalSince1970:totalFloatTim];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    if (totalFloatTim / 3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    }else {
        [formatter setDateFormat:@"mm:ss"];
    }
    
    NSString *presentStrTime = [formatter stringFromDate:presentDate];
    
    NSString *totalStrTime = [formatter stringFromDate:totalDate];
    
    NSString *string = [NSString stringWithFormat:@"%@/%@", presentStrTime, totalStrTime];
    
    self.timeLabel.text = string;
    
    self.timeLabel.textColor = [UIColor whiteColor];
    
    [self.BtuClickView addSubview:self.timeLabel];
}


#pragma mark - 全屏与小屏
- (void)plusButtonAction:(UIButton *)sender {
    
    if (_isplus == YES) {
        
        self.navigationController.navigationBar.hidden  = YES;
        self.navigationController.navigationBar.translucent = YES;
        self.tabBarController.tabBar.hidden = YES;
        
        self.playView.transform = CGAffineTransformMakeRotation(M_PI / 2);
        self.playView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        [self.view addSubview:_playView];
        self.MVPlayer.playerLayer.frame = _playView.bounds;
        // 添加点击事件
        [_playClickbutton addTarget:self action:@selector(clickbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.BtuClickView addSubview:self.playClickbutton];
        _isplay = YES;

        self.BtuClickView.frame = CGRectMake(0, self.playView.bounds.size.height * 0.9, self.playView.bounds.size.width, self.playView.bounds.size.height * 0.1);
        
        self.slider.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.1, 0, self.BtuClickView.frame.size.width * 0.6, self.BtuClickView.frame.size.height);
        
        self.timeLabel.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.78, 0, self.BtuClickView.frame.size.width * 0.15, self.BtuClickView.frame.size.height);
        
        self.playClickbutton.frame = CGRectMake(15, 2.5, self.BtuClickView.frame.size.height - 5, self.BtuClickView.frame.size.height - 5);
        
        self.plusButton.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.92, 0, self.BtuClickView.frame.size.height, self.BtuClickView.frame.size.height);
        [_plusButton setImage:[[UIImage imageNamed:@"视频小屏"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        
        _backButton.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.05 + 13, 10, 20, 20);
        
        _goButton.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.7, 10, 20, 20);
        
        self.speedView.frame = CGRectMake(0, 0, HEIGHT, _playView.bounds.size.height * 0.1);
        
        _delectButton.frame = CGRectMake(HEIGHT * 0.95, 0, 20, 20);
        
        _isplus = NO;
        
        
    } else {
        
        self.navigationController.navigationBar.hidden  = NO;
        self.navigationController.navigationBar.translucent = NO;
        self.tabBarController.tabBar.hidden = NO;
        
        self.playView.transform = CGAffineTransformIdentity;
        self.playView.frame = CGRectMake(0, 0, WIDTH, HEIGHT * 0.3 + 20);
        [self.topView addSubview:_playView];
        self.MVPlayer.playerLayer.frame = _playView.bounds;
        UITapGestureRecognizer *playViewTap = [[UITapGestureRecognizer alloc] init];
        [playViewTap addTarget:self action:@selector(playViewTapAction:)];
        [_playView addGestureRecognizer:playViewTap];
        _isHidden = YES;
        
        self.BtuClickView.frame = CGRectMake(0, self.playView.bounds.size.height * 0.9, self.playView.bounds.size.width, self.playView.bounds.size.height * 0.1);
        
        self.playClickbutton.frame = CGRectMake(5, 0, self.BtuClickView.frame.size.height, self.BtuClickView.frame.size.height);
        
        self.slider.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.15, 5, self.BtuClickView.frame.size.width * 0.4, self.BtuClickView.bounds.size.height - 10);
        
        self.timeLabel.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.6, 0, self.BtuClickView.frame.size.width * 0.3, self.BtuClickView.frame.size.height);
        
        _plusButton.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.9, 0, 20, 20);
        [_plusButton setImage:[[UIImage imageNamed:@"视频全屏"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        
        _backButton.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.1, 0, 20, 20);
        
        _goButton.frame = CGRectMake(self.BtuClickView.frame.size.width * 0.55 - 3, 0, 20, 20);
        
        self.speedView.frame = CGRectMake(0, 0, self.playView.bounds.size.width, self.playView.bounds.size.height * 0.1);
        
        _delectButton.frame = CGRectMake(self.speedView.frame.size.width * 0.95, 0, self.speedView.bounds.size.height, self.speedView.bounds.size.height);
        
        _isplus = YES;
        
    }
    
}

#pragma mark - 快进与快退
- (void)backButtonAction:(UIButton *)sender {
    
    
    
}

- (void)goButtonAction:(UIButton *)sender {
    
    
    
}

#pragma mark - 取消按钮
- (void)delectButtonAction:(UIButton *)sender {
    
    if (_isplus == NO) {
        
        self.navigationController.navigationBar.hidden  = NO;
        self.navigationController.navigationBar.translucent = NO;
        self.tabBarController.tabBar.hidden = NO;
        
    }
    [_playView removeFromSuperview];
    [_MVPlayer pause];
    
}

/**
 *  tableView协议方法实现
 */

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.dataSource.count == 0) {
        return 0;
    }
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MovieDataModel *model = self.dataSource[indexPath.row];
    
    _cellHeight = [MovieDetailTableViewCell heightWithText:model.content];
    
    return _cellHeight + 120;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MovieDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"movieDetail"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.dataModel = self.dataSource[indexPath.row];
    
    return cell;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
